
import ApiUrl from './ApiUrl'
/**
 * @description get Open Id from wechat auth
 */
function getOpenId(cb){
    wx.login({
      success: function(res) {
         console.log( 'wechat login success', res );
         if (res.code) {
            //  wx.getUserInfo({
            //      withCredentials: true,
            //      success: function(result){
            //          console.log( '000000000000000', result );
            //      }
            //  })
          //发起网络请求
          wx.request({
            url: 'https://mtest.quantumhealth.cn/miniWechat/getWechatMiniOpenId',
            method: 'POST',
            data: {
              code: res.code
            },
            success:function(res2){
                console.log( 'get openId success', res2 );
                try {
                    if( res2.statusCode == 200 ){
                        wx.setStorageSync('openId', res2.data.openid)
                        typeof cb === 'function' && cb( res2.data.openid )
                    }
                } catch (e) {   
                    console.error( 'e.message', e.message ); 
                }
            },
            fail: function(res2){
                console.log( 'get openId failed', res2 );
            }
          })
         } else {
           console.log('获取用户登录态失败！' + res.errMsg)
         }
       }
    });
}
/**
 * @description user quantumhealth account login
 */
function login(){
   return new Promise(function(resolve, reject){
        getOpenId(function(openId){
            wx.request({
                url: ApiUrl.login.url,
                method: ApiUrl.login.method,
                data:{
                    wechat_id: openId,
                    entry: 'customer'
                },
                success: function(result){
                    if( result.data.status_code == 401 ){
                        wx.redirectTo({ url: '/pages/auth/login/login'});
                        reject();
                    }
                    if( result.data.token ){
                        wx.setStorageSync( 'token', result.data.token );
                        resolve();
                    }
                    console.log( 'login finished', result );
                }
            })
       })
   }) 
}


module.exports = {
    login: login,
};